<template>
    <!-- 导航栏 -->
    <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/overview' }">
            <h3>首页</h3>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
            <h3>用户管理</h3>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
            <h3>添加用户</h3>
        </el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加一个卡片  -->
    <el-card class="box-card">
        <!-- 搜索和添加区域     gutter 间隔 -->
        
        <el-row :gutter="20">
            <el-col :span="8">
                <el-input placeholder="请输入用户名" 
                v-model="queryinfo.query"    
                
                class="input-with-select">
                    <template #append>
                        <el-button :icon="Search" @click="sear_user" />
                    </template>
                </el-input>
            </el-col>

            <el-col :span="4">
                <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
            </el-col>

            <el-col :span="4">
                <el-button type="primary" @click="userlist">查询列表</el-button>
            </el-col>

        </el-row>

        <!-- 用户列表 -->
        <el-table :data="dd.tableData" border="true" style="width: 100%" stripe highlight-current-row>
            <el-table-column type="index" />
            <el-table-column prop="name" label="用户名" width="220" />
            <el-table-column prop="passwd" label="密码" width="220" />
            <el-table-column prop="createTime" label="日期" width="280" />
            <el-table-column prop="role" label="角色" width="220" />
            <el-table-column label="状态" width="220">
                <!-- 作用域 插槽  渲染一个switch -->
                <template #default="scope">
                    <!--scope.row  获取这一行的数据   -->
                    <!-- {{ scope.row }}          -->
                    <!-- change 是一个event -->
                    <el-switch v-model=scope.row.status @change="userstatechanged(scope.row)" />

                </template>

            </el-table-column>
            <el-table-column prop="operation" label="操作" width='170px' resizable>
                <!-- 作用域插槽  -->
                <template #default="scope">
                    <!-- 编辑 ，并增加tips提示, 遮挡的时间自动隐藏-->
                    <el-tooltip effect="dark" content="Edit" placement="top" :enterable="false">
                        <el-button type="primary" :icon="Edit" />
                    </el-tooltip>
                    <!-- 删除， 并增加Tooltip 文字提示，遮挡的时间自动隐藏-->
                    <el-tooltip effect="dark" content="Delete" placement="top" :enterable="false">
                        <el-button type="danger" :icon="Delete" @click="deleteRow(scope.$index, scope.row)" />
                    </el-tooltip>

                    <!-- <el-button type="text"
                         size="small" @click="searchc(scope.$index,scope.row.taskid)">
                查看 -->
                    <!-- </el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加dialog对话框Ian -->
        <el-dialog v-model="dialogVisible" title="添加角色" width="30%" draggable center>
            <div style="margin: 20px" />

            <el-form :label-position="labelPosition" label-width="100px" :model="formLabelAlignmodel"
                style="max-width: 460px" status-icon :rules="rules" ref="formLabelAlign">

                <el-form-item label="账户 :" prop="name">
                    <el-input v-model="formLabelAlignmodel.name" />
                </el-form-item>
                <el-form-item label="密码 :" prop="passwd">
                    <el-input type='password' v-model="formLabelAlignmodel.passwd" />
                </el-form-item>


                <el-form-item label="角色选择 " prop="role">
                    <el-select v-model="formLabelAlignmodel.role" placeholder="角色选择">
                        <el-option label="子管理员" value="子管理员" />
                        <el-option label="总管理员" value="总管理员" />
                    </el-select>
                </el-form-item>

            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleadduser()">确定</el-button>
                </span>
            </template>


        </el-dialog>

        <!-- 分页 页码 -->
        <el-row :gutter="20">
            <el-col :span="12" :offset="6">
                <!-- 分页 -->
                <el-pagination v-model:currentPage="queryinfo.pagenum" v-model:page-size="queryinfo.pagesize"
                    :page-sizes="[1, 2, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="dd.total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />

            </el-col>
        </el-row>


    </el-card>


</template>




<script setup>
import { ref, reactive } from 'vue'               //处理响应式数据 ,需要导入
import { ArrowRight, Search, Delete, Edit } from '@element-plus/icons-vue'     //图标

import { getUserList, adduser, searchuser,
deleteuser, userstate } from '../../../api/index'
import { create } from 'lodash';
import { ElMessage } from 'element-plus';



const dialogVisible = ref(false)

//这里定义的是发送请求带的参数 可以有 ,也可以不要
const queryinfo = reactive({
    query: '',
    // page页码
    pagenum: 1,
    // 当前每页 ，page页列表数量
    pagesize: 5
})


// 模糊查询用户
function sear_user (){
    searchuser(queryinfo).then( res =>{
            console.log(queryinfo);
            console.log(res.data.code);
            // 存放到list表中展示到UI上
             dd.tableData = res.data.res
             dd.total = res.data.total

            queryinfo.query = ""




    }).catch(res =>{
            console.log(res.data.code);
    }    )
}

// switch开关改变事件   userinfo 是参数
function userstatechanged(userinfo) {
    console.log(userinfo)

    userstate(userinfo).then(res => {
        console.log(res.data.code)

        if (res.data.code !== 200) {
            ElMessage({
                message: res.data.msg,
                type: 'error',
            })
            // 如果更新失败了,页面上更新了,数据库没有更新,所以要把页面的数据给修改回来
            userinfo.status = !userinfo.status
        } else {
            ElMessage({
                message: res.data.msg,
                type: 'success',
            })
        }

    }).catch(err => {
        console.log('连接失败!');
        ElMessage({
            message: "连接失败",
            type: 'error',
        })
    })

}

// const 修饰的标识符被赋值之后，不能修改,必须赋值 ,但是可以修改里面的属性数据  
const dd = reactive({
    //数组的大小
    total: 0,
    // 数据  
    tableData: []
})


// 添加用户 传参 
const formLabelAlignmodel = reactive({
    name: '',
    passwd: '',
    role: ''
})


// 校验规则   prop 校验 
const rules = reactive({
    name: [{ required: true, message: "必须填写", trigger: 'blur' },
     { min: 5, message: "长度最少是5", trigger: 'blur' },],
    passwd: [{ required: true, message: "必须填写", trigger: 'blur' },
     { min: 5, message: "长度最少是5", trigger: 'blur' },],
    role: [{
        required: true,
        message: '请选择管理员的类型',
        trigger: 'blur',
    },]
})

// 触发请求后, 数据
const formLabelAlign = ref(null)

//添加用户 
function handleadduser() {
    console.log(formLabelAlign.value)

    formLabelAlign.value.validate(isValid => {              //只有在校验正确的情况下,才触发请求 
        if (isValid) {
            adduser(formLabelAlignmodel).then(res => {
                console.log(res)
                ElMessage({
                    message: res.data['message'],
                    type: 'warning',
                })


                //关闭对话框 
                dialogVisible.value = !dialogVisible.value
                //在请求一次 
                userlist()
            }
            )
        }
        else {
            ElMessage({
                message: '请输入正确的信息再提交',
                type: 'warning',
            })
        }




    })
}

create()
{     //进入到界面默认执行里面的代码
    userlist()
}



// 获取用户的列表 ，从后台数据库中获取到
function userlist() {
    // return tableData
    getUserList(queryinfo).then(Response => {
        console.log(Response)
        if (Response.data['code'] === 200) {
            // 这里获取到的数据要一一对应才可以正常显示出来 ,否则是无法正常显示,要按照tableData1的格式进行返回
            dd.tableData = Response.data.res
            dd.total = Response.data.total
        }

        else {
            ElMessage({
                message: '获取数据失败!',
                type: 'success',
            })
        }
    }).catch( res =>{
        ElMessage({
                message: '请求错误!',
                type: 'error',
            })
    })
}


//删除行数据
const deleteRow = (index, $row) => {
    console.log($row.name);
    console.log(index);

    const data = reactive({
        name: $row.name
    })
    deleteuser(data).then(res => {
        console.log(res);
    })

    dd.tableData.splice(index, 1)


};

//监听pagesize 页码值改变, 页面每次显示多个数据 limit 限制
function handleSizeChange(newsize) {
    console.log(newsize)
    //保存下改变的值 ,就是一页显示几个 
    queryinfo.pagesize = newsize

    //需要再次请求下数据 ,重新进行请求 
    userlist()


}

// 监听当前的页码改变 
function handleCurrentChange(newpage) {
    console.log(newpage)

    queryinfo.pagenum = newpage
    // 重新获取数据 
    userlist()
}

</script>


<style lang="less" scoped>
.box-card {
    height: 100%;
}

.el-table {
    margin-top: 10px;
}
</style>